package com.example.stlink.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.stlink.R;
import com.example.stlink.configs.adapter.StuDeleteCourseAdapter;
import com.example.stlink.configs.onRecyclerViewItemClickListener;
import com.example.stlink.activitys.fragmentChild.activityStuHome.AllCourses;
import com.example.stlink.activitys.fragmentChild.activityTeaCourse.CourseDetail;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.Course;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseData;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import gdut.bsx.view.FloatDragPopupWindow;

public class StuHomeFragment extends Fragment {

    private static FloatingActionButton faButton;
    private static AppCompatButton codeButton;
    private static AppCompatButton wordButton;
    private static RecyclerView rvStuCourseList;
    private static ConstraintLayout clFragStuHome;
    private static SwipeRefreshLayout srlMyRefresh;

    private static AppCompatActivity mAppCompatActivity;

    private static List<Course> courseList;
    private static StuDeleteCourseAdapter adapter;

    private static Bundle bundle;
    private static Handler handler;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_stu_home, container, false);
        mAppCompatActivity = (AppCompatActivity) getActivity();
        initView(view);
        return view;
    }

    public static StuHomeFragment newInstance(String str){
        StuHomeFragment frag = new StuHomeFragment();
        return frag;
    }

    /**
     * 初始化布局
     * @param view 当前布局
     */
    private static void initView(View view){
        codeButton = view.findViewById(R.id.bt_code_check);
        wordButton = view.findViewById(R.id.bt_word_check);
        faButton = view.findViewById(R.id.floating_action_button);
        rvStuCourseList = view.findViewById(R.id.rv_stu_course_list);
        clFragStuHome = view.findViewById(R.id.cl_frag_stu_home);
        srlMyRefresh = view.findViewById(R.id.srl_my_refresh);
        srlMyRefresh.setColorSchemeColors(Color.parseColor("#ff0000"),Color.parseColor("#00ff00"));


        //先把父布局里的该按钮给移除
        clFragStuHome.removeView(faButton);
        // 创建 FloatDragPopupWindow，并将 contentView 添加到布局中
        FloatDragPopupWindow floatDragPopupWindow = new FloatDragPopupWindow.Builder(mAppCompatActivity)
                .setContentView(faButton)
                .setPosition(0, 600)
                .setOnClickListener(v -> {
                    Intent intent = new Intent(mAppCompatActivity, AllCourses.class);
                    intent.putExtras(mAppCompatActivity.getIntent().getExtras());
                    mAppCompatActivity.startActivity(intent);
                })
                .build();
        // 显示 FloatDragPopupWindow
        floatDragPopupWindow.show();

        setListener(view);

        refreshData();
    }

    /**
     * 为按钮添加点击监听事件
     * @param view 当前布局
     */
    private static void setListener(View view){
        //口令输入 TODO
        codeButton.setOnClickListener(v -> {

        });
        //文本输入 TODO
        wordButton.setOnClickListener(v -> {

        });
        faButton.setOnClickListener(v -> {

        });
        srlMyRefresh.setOnRefreshListener(() -> {
            refreshData();
            srlMyRefresh.setRefreshing(false);
        });
    }


    /**
     * 刷新数据
     */
    public static void refreshData(){
        courseList = new ArrayList<>();
        adapter = new StuDeleteCourseAdapter(
                mAppCompatActivity,
                R.layout.card_course_tea,
                courseList,
                0
        );
        LinearLayoutManager llm = new LinearLayoutManager(mAppCompatActivity);
        rvStuCourseList.setLayoutManager(llm);
        rvStuCourseList.setAdapter(adapter);

        bundle = mAppCompatActivity.getIntent().getExtras();
        handler = new Handler(Looper.getMainLooper()){
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.arg1 == 100){
                    System.out.println("courseList = " + courseList.toString());
                    adapter.notifyDataSetChanged();
                }
            }
        };
        getStuSelectedCourseList();

        setItemClickListener();
    }

    /**
     * 添加点击事件
     */
    public static void setItemClickListener(){
        adapter.setOnItemClickListener(new onRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Intent intent = new Intent(mAppCompatActivity, CourseDetail.class);
                bundle = mAppCompatActivity.getIntent().getExtras();
                //将position传入bundle
                Long courseId = courseList.get(position).getmCourseId();
                bundle.putLong(ModelFieldConstants.COURSE_ID, courseId);
                System.out.println("courseId == " + courseId);
                System.out.println("course == " + courseList.get(position));
                System.out.println("bundle:courseId == " + bundle.getLong(ModelFieldConstants.COURSE_ID));
                System.out.println("bundle:userId == " + bundle.getLong(ModelFieldConstants.USER_ID));
                intent.putExtras(bundle);
                mAppCompatActivity.startActivity(intent);
            }

            @Override
            public void onItemLongClick(RecyclerView parent, View view, int position) { }
        });
    }

    private static void getStuSelectedCourseList(){
        new Thread(new Runnable() {
            final String urlParam = ModelFieldConstants.USER_ID + "=" + bundle.getLong(ModelFieldConstants.ID);
            final String url = UrlConstants.STUDENT_COURSE + "?" + urlParam;
            @Override
            public void run() {
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {

                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        String jsonString = gson.toJson(courseDataMap);
                        CourseData<Course> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<Course>>() {}.getType());

                        List<Course> records = courseData.getRecords();

                        courseList.addAll(records);

                        Message message = new Message();
                        message.arg1 = 100;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) { }
                }.getConnect(url);
            }
        }).start();
    }

}
